package com.example.videoconverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Arrays;
import java.util.Map;
import java.util.Scanner;

/**
 * 视频转换器演示程序
 * 展示AVI转MP4功能的使用方法
 */
public class VideoConverterDemo {
    private static final Logger logger = LoggerFactory.getLogger(VideoConverterDemo.class);
    private static final Scanner scanner = new Scanner(System.in);
    
    public static void main(String[] args) {
        logger.info("=== 视频转换器演示程序 ===");
        logger.info("基于FFmpeg和JavaCV的AVI转MP4转换工具");
        logger.info("");
        
        VideoConverter converter = new VideoConverter();
        
        try {
            if (args.length >= 2) {
                // 命令行模式
                String inputPath = args[0];
                String outputPath = args[1];
                double frameRate = args.length > 2 ? Double.parseDouble(args[2]) : 25.0;
                
                runConversion(converter, inputPath, outputPath, frameRate);
            } else {
                // 交互模式
                runInteractiveMode(converter);
            }
        } catch (Exception e) {
            logger.error("程序执行出错: {}", e.getMessage(), e);
            System.exit(1);
        }
    }
    
    /**
     * 运行交互模式
     */
    private static void runInteractiveMode(VideoConverter converter) throws Exception {
        while (true) {
            System.out.println("\n=== 视频转换器菜单 ===");
            System.out.println("1. AVI转MP4 (标准转换)");
            System.out.println("2. AVI转MP4 (简化转换，无JavaCV依赖)");
            System.out.println("3. 查看视频信息");
            System.out.println("4. 提取视频帧");
            System.out.println("5. 创建测试视频");
            System.out.println("6. 验证视频文件");
            System.out.println("0. 退出");
            System.out.print("请选择操作 (0-6): ");
            
            int choice = getIntInput();
            
            switch (choice) {
                case 1:
                    handleVideoConversion(converter);
                    break;
                case 2:
                    handleSimpleVideoConversion(converter);
                    break;
                case 3:
                    handleVideoInfo(converter);
                    break;
                case 4:
                    handleFrameExtraction();
                    break;
                case 5:
                    handleCreateTestVideo();
                    break;
                case 6:
                    handleVideoValidation();
                    break;
                case 0:
                    System.out.println("感谢使用视频转换器！");
                    return;
                default:
                    System.out.println("无效选择，请重试。");
            }
        }
    }
    
    /**
     * 处理视频转换
     */
    private static void handleVideoConversion(VideoConverter converter) throws Exception {
        System.out.print("请输入输入AVI文件路径: ");
        String inputPath = scanner.nextLine().trim();
        
        if (!new File(inputPath).exists()) {
            System.out.println("错误: 输入文件不存在!");
            return;
        }
        
        System.out.print("请输入输出MP4文件路径: ");
        String outputPath = scanner.nextLine().trim();
        
        System.out.print("请输入帧率 (默认25): ");
        String frameRateStr = scanner.nextLine().trim();
        double frameRate = frameRateStr.isEmpty() ? 25.0 : Double.parseDouble(frameRateStr);
        
        runConversion(converter, inputPath, outputPath, frameRate);
    }
    
    /**
     * 处理简化视频转换（不依赖JavaCV）
     */
    private static void handleSimpleVideoConversion(VideoConverter converter) throws Exception {
        System.out.println("\n=== 简化AVI转MP4转换 ===");
        System.out.println("注意: 此方法仅使用JAVE库，不依赖JavaCV/OpenCV");
        
        System.out.print("请输入输入AVI文件路径: ");
        String inputPath = scanner.nextLine().trim();
        
        if (!new File(inputPath).exists()) {
            System.out.println("错误: 输入文件不存在!");
            return;
        }
        
        System.out.print("请输入输出MP4文件路径: ");
        String outputPath = scanner.nextLine().trim();
        
        runSimpleConversion(converter, inputPath, outputPath);
    }
    
    /**
     * 执行视频转换
     */
    private static void runConversion(VideoConverter converter, String inputPath, String outputPath, double frameRate) throws Exception {
        System.out.println("\n开始转换...");
        System.out.println("输入文件: " + inputPath);
        System.out.println("输出文件: " + outputPath);
        System.out.println("帧率: " + frameRate + " fps");
        
        long startTime = System.currentTimeMillis();
        
        try {
            // 显示输入视频信息
            Map<String, Object> inputInfo = converter.getVideoInfo(inputPath);
            System.out.println("\n输入视频信息:");
            System.out.println(inputInfo.toString());
            
            // 执行转换
            converter.convertAviToMp4(inputPath, outputPath, frameRate);
            
            long endTime = System.currentTimeMillis();
            double duration = (endTime - startTime) / 1000.0;
            
            // 显示输出视频信息
            Map<String, Object> outputInfo = converter.getVideoInfo(outputPath);
            System.out.println("\n输出视频信息:");
            System.out.println(outputInfo.toString());
            
            // 显示文件大小对比
            File inputFile = new File(inputPath);
            File outputFile = new File(outputPath);
            
            System.out.println("\n=== 转换完成 ===");
            System.out.printf("转换耗时: %.2f 秒%n", duration);
            System.out.printf("输入文件大小: %.2f MB%n", inputFile.length() / (1024.0 * 1024.0));
            System.out.printf("输出文件大小: %.2f MB%n", outputFile.length() / (1024.0 * 1024.0));
            System.out.printf("压缩比: %.2f%%%n", (double) outputFile.length() / inputFile.length() * 100);
            
        } catch (Exception e) {
            System.err.println("转换失败: " + e.getMessage());
            throw e;
        }
    }
    
    /**
     * 执行简化视频转换
     */
    private static void runSimpleConversion(VideoConverter converter, String inputPath, String outputPath) throws Exception {
        System.out.println("\n开始简化转换...");
        System.out.println("输入文件: " + inputPath);
        System.out.println("输出文件: " + outputPath);
        System.out.println("转换模式: 简化模式 (仅JAVE库)");
        
        long startTime = System.currentTimeMillis();
        
        try {
            // 显示输入视频信息
            Map<String, Object> inputInfo = converter.getVideoInfo(inputPath);
            System.out.println("\n输入视频信息:");
            System.out.println(inputInfo.toString());
            
            // 执行简化转换
            converter.simpleConvertAviToMp4(inputPath, outputPath);
            
            long endTime = System.currentTimeMillis();
            double duration = (endTime - startTime) / 1000.0;
            
            // 显示输出视频信息
            Map<String, Object> outputInfo = converter.getVideoInfo(outputPath);
            System.out.println("\n输出视频信息:");
            System.out.println(outputInfo.toString());
            
            // 显示文件大小对比
            File inputFile = new File(inputPath);
            File outputFile = new File(outputPath);
            
            System.out.println("\n=== 简化转换完成 ===");
            System.out.printf("转换耗时: %.2f 秒%n", duration);
            System.out.printf("输入文件大小: %.2f MB%n", inputFile.length() / (1024.0 * 1024.0));
            System.out.printf("输出文件大小: %.2f MB%n", outputFile.length() / (1024.0 * 1024.0));
            System.out.printf("压缩比: %.2f%%%n", (double) outputFile.length() / inputFile.length() * 100);
            System.out.println("转换方式: 简化模式 (无JavaCV依赖)");
            
        } catch (Exception e) {
            System.err.println("简化转换失败: " + e.getMessage());
            throw e;
        }
    }
    
    /**
     * 处理查看视频信息
     */
    private static void handleVideoInfo(VideoConverter converter) throws Exception {
        System.out.print("请输入视频文件路径: ");
        String videoPath = scanner.nextLine().trim();
        
        if (!new File(videoPath).exists()) {
            System.out.println("错误: 文件不存在!");
            return;
        }
        
        try {
            Map<String, Object> info = converter.getVideoInfo(videoPath);
            System.out.println("\n=== 视频信息 ===");
            System.out.println(info.toString());
            
            // 额外信息
            File file = new File(videoPath);
            System.out.printf("文件大小: %.2f MB%n", file.length() / (1024.0 * 1024.0));
            System.out.println("文件路径: " + file.getAbsolutePath());
            System.out.println("最后修改: " + new java.util.Date(file.lastModified()));
            
        } catch (Exception e) {
            System.err.println("获取视频信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理帧提取
     */
    private static void handleFrameExtraction() throws Exception {
        System.out.print("请输入视频文件路径: ");
        String videoPath = scanner.nextLine().trim();
        
        if (!new File(videoPath).exists()) {
            System.out.println("错误: 文件不存在!");
            return;
        }
        
        System.out.print("请输入输出目录: ");
        String outputDir = scanner.nextLine().trim();
        
        System.out.print("请输入要提取的帧数: ");
        int frameCount = getIntInput();
        
        try {
            int extractedCount = VideoUtils.extractFramesEvenly(videoPath, outputDir, frameCount);
            System.out.println("\n成功提取 " + extractedCount + " 帧到目录: " + outputDir);
            
            // 显示提取的文件
            File dir = new File(outputDir);
            File[] imageFiles = dir.listFiles((d, name) -> name.endsWith(".png"));
            if (imageFiles != null && imageFiles.length > 0) {
                System.out.println("提取的图片文件:");
                Arrays.stream(imageFiles)
                      .limit(5) // 只显示前5个
                      .forEach(f -> System.out.println("  " + f.getName()));
                if (imageFiles.length > 5) {
                    System.out.println("  ... 还有 " + (imageFiles.length - 5) + " 个文件");
                }
            }
            
        } catch (Exception e) {
            System.err.println("帧提取失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理创建测试视频
     */
    private static void handleCreateTestVideo() throws Exception {
        System.out.print("请输入输出视频路径 (如 test.avi): ");
        String outputPath = scanner.nextLine().trim();
        
        System.out.print("请输入视频宽度 (默认640): ");
        String widthStr = scanner.nextLine().trim();
        int width = widthStr.isEmpty() ? 640 : Integer.parseInt(widthStr);
        
        System.out.print("请输入视频高度 (默认480): ");
        String heightStr = scanner.nextLine().trim();
        int height = heightStr.isEmpty() ? 480 : Integer.parseInt(heightStr);
        
        System.out.print("请输入视频时长(秒) (默认5): ");
        String durationStr = scanner.nextLine().trim();
        double duration = durationStr.isEmpty() ? 5.0 : Double.parseDouble(durationStr);
        
        System.out.print("请输入帧率 (默认25): ");
        String frameRateStr = scanner.nextLine().trim();
        double frameRate = frameRateStr.isEmpty() ? 25.0 : Double.parseDouble(frameRateStr);
        
        try {
            System.out.println("\n正在创建测试视频...");
            // TODO: 实现测试视频创建功能
            System.out.println("测试视频创建功能暂未实现");
            
            File testFile = new File(outputPath);
            System.out.println("测试视频创建成功!");
            System.out.println("文件路径: " + testFile.getAbsolutePath());
            System.out.printf("文件大小: %.2f MB%n", testFile.length() / (1024.0 * 1024.0));
            
        } catch (Exception e) {
            System.err.println("创建测试视频失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理视频验证
     */
    private static void handleVideoValidation() {
        System.out.print("请输入视频文件路径: ");
        String videoPath = scanner.nextLine().trim();
        
        boolean isValid = VideoUtils.isValidVideo(videoPath);
        
        System.out.println("\n=== 验证结果 ===");
        System.out.println("文件路径: " + videoPath);
        System.out.println("文件存在: " + new File(videoPath).exists());
        System.out.println("有效视频: " + (isValid ? "是" : "否"));
        
        if (new File(videoPath).exists()) {
            File file = new File(videoPath);
            System.out.printf("文件大小: %.2f MB%n", file.length() / (1024.0 * 1024.0));
        }
    }
    
    /**
     * 获取整数输入
     */
    private static int getIntInput() {
        while (true) {
            try {
                return Integer.parseInt(scanner.nextLine().trim());
            } catch (NumberFormatException e) {
                System.out.print("请输入有效的数字: ");
            }
        }
    }
}